﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.DataEntify;
using FastReport;
using System.IO;
using System.Web.UI.WebControls;

namespace biaoqian
{
    public partial class APS_XBQ : Form
    {
        Class1 one = new Class1();
        LDhuoyunEntities db = new LDhuoyunEntities();

        public APS_XBQ()
        {
            InitializeComponent();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void APS_XBQ_Load(object sender, EventArgs e)
        {
            GET_GXJHLB();
        }
        private void GET_GXJHLB()
        {
            string text1 = comboBox1.Text;

            DateTime previoustime = DateTime.Parse(dateTimePicker1.Text).AddDays(-1);
            string previoustime2 = previoustime.ToString("yyyy-MM-dd");
            DateTime nexttime = DateTime.Parse(dateTimePicker1.Text).AddDays(1);
            string nexttime2 = nexttime.ToString("yyyy-MM-dd");
            if (text1 != null && text1 != "")
            {
                previoustime2 = "2000/1/11";
                nexttime2 = "3000/1/11";
            }
            previoustime2 = previoustime2 + " 23:59:59";
            nexttime2 = nexttime2 + " 00:00:01";
            K3CloudApi client = new K3CloudApi();
            //用于记录结果
            StringBuilder Info = new StringBuilder();
            //业务对象标识
            string formId = "SFC_OperationPlanning";//SFC_OperationPlanning
            //查询字段集合，即返回哪些数据，不能为空，根据不同业务单据填写不同的字段名，以下仅为示例
            string fieldKeys = "FMONumber,FProductId.FNumber,FMOQty,FProSpecification,FSeqPlanStartTime,F_SMGS_Text,FProductName,F_SMGS_BaseProperty";
            //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
            //"FMONumber like'%" + ZBLx + "%' and  FSeqPlanStartTime>'" + previoustime2 + "'and FSeqPlanStartTime<'" + nexttime2 + "' and (F_SMGS_Text='末工序FinalProcess' or F_SMGS_Text='首末工序First&FinalProcess')"
            var ZBLx = text1;
            var param = new QueryParam()
            {
                FormId = formId,
                FieldKeys = fieldKeys,
                FilterString = "FMONumber like'%" + ZBLx + "%'and F_SMGS_BaseProperty='龙口海盟' and  FSeqPlanStartTime>'" + previoustime2 + "'and FSeqPlanStartTime<'" + nexttime2 + "')",
                TopRowCount = 0,
                StartRow = 0,
                Limit = 120,
                OrderString = "FMONumber",
            };
            //调用接口
            var result = client.ExecuteBillQuery(param.ToJson());
            if (dataGridView1.Columns.Count != 0)
            {
                dataGridView1.Columns.Clear();
            }
            /* JsonSerializerSettings settings = new JsonSerializerSettings();
             string jsongStr = JsonConvert.SerializeObject(result, settings);*/
            //转换成标准文档并遍历
            int index = 1;
            DataTable dataTable = one.gyjh();
            foreach (var item in result)
            {
                dataTable.Rows.Add(index, item[0], item[1], item[2], item[3], item[4], item[5], item[6]);
                index++;
            }
            dataGridView1.DataSource = dataTable;
            
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            GET_GXJHLB();
        }

        private string getString_KHBM(string input)
        {
            string startChar = "("; // 开始字符  
            char endChar = ')'; // 结束字符（注意：这包括结束字符本身）  

            // 查找开始字符和结束字符的索引  
            int startIndex = input.IndexOf(startChar);
            if (startIndex == -1)
            {
                startChar = "（"; // 开始字符  
                startIndex = input.IndexOf(startChar);
            }
            int endIndex = input.IndexOf(endChar, startIndex); // 从startIndex开始查找endChar  
            if (endIndex == -1)
            {
                endChar = '）';
                endIndex = input.IndexOf(endChar, startIndex);
            }
            // 提取子字符串（包括开始字符和结束字符）  
            // 注意：endIndex - startIndex + 1 是因为我们需要包括结束字符在内  
            string result = input.Substring(startIndex, endIndex - startIndex + 1);
            
            // 如果你不希望结果中包含结束字符，可以稍微调整endIndex或结果字符串  
            // 例如，去除结果字符串中的结束字符  
            if (result.EndsWith(endChar.ToString()))
            {
                result = result.Substring(0, result.Length - 1);
            }
            return result;
        }

        private string getString_WLMC(string input)
        {
            string startString = "18A"; // 开始字符  
            char endChar = '('; // 结束字符（注意：这包括结束字符本身）  

            // 查找开始字符串的索引  
            int startIndex = input.IndexOf(startString) + startString.Length;
            

            // 查找结束字符的索引（从startIndex开始查找）  
            int endIndex = input.IndexOf(endChar, startIndex);
            if (endIndex == -1)
            {
                endChar = '(';
                endIndex = input.IndexOf(endChar, startIndex);
            }

            // 提取子字符串（不包括结束字符）  
            string result = input.Substring(startIndex, endIndex - startIndex);
            return "18A"+result;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string hang = textBox1.Text;
            DataTable dataTable = one.ERP_cgdd();
            if (hang == null)
            {
                MessageBox.Show("请先选择行号");

            }
            else
            {
                foreach (DataGridViewRow data in dataGridView1.Rows)
                {
                    string blbh = data.Cells[2].Value.ToString();
                    string gg = data.Cells[4].Value.ToString();
                    DateTime riqi2 = DateTime.Parse(data.Cells[5].Value.ToString());
                    string sl = data.Cells[3].Value.ToString();
                    string riqi = riqi2.ToString("yyyy-MM-dd");

                    if (data.Cells[0].Value.ToString() == hang)
                    {
                        string zjm = "";
                        string daobao = "";
                        string daobao2 = "";
                        string FName = "";
                        string F_land_Text = "";
                        DataTable wlxx = GET_WUliao(data.Cells[2].Value.ToString());
                        foreach (DataRow data5 in wlxx.Rows)
                        {
                            daobao = data5[0].ToString();
                            daobao2 = data5[0].ToString();
                            zjm = data5[1].ToString();
                            FName = data5[2].ToString();
                            F_land_Text = data5[3].ToString();
                        }
                        string khbm = getString_KHBM(FName);
                        string wlmc = getString_WLMC(FName);
                        string bz = GET_KHWLDY(blbh);

                        DataTable xbqm1 = one.XbiaoqM1();

                        if (daobao2 == "0" || daobao2==null)
                        {
                            daobao2 = "10";
                            daobao = "10";
                        }
                        int Printtimes = int.Parse(sl) / int.Parse(daobao2) + 2;
                        xbqm1.Rows.Add(FName, blbh, khbm, daobao, riqi, Printtimes);

                        DataSet da = new DataSet();
                        da.Tables.Add(xbqm1);
                        xbqm1.TableName = "Table1";
                        //模板1
                        //string baseDirectory1 = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
                        string physicalPath1 = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Production label\\APS_XBQ.frx");

                        Report report1 = new Report();
                        report1.Load(physicalPath1);//打开文件/*
                        report1.RegisterData(da);//绑定数据源
                                                 //webReport.Report.SetParameterValue("ksnfjidn", Appbian);//替换fastreport参数的值--
                        DataBand data1 = report1.Report.FindObject("Data1") as DataBand;
                        data1.DataSource = report1.Report.GetDataSource("Table1");
                        report1.PrintSettings.Copies = Printtimes;
                        report1.Prepare();
                        report1.ShowPrepared();
                    }
                }
            }
            GET_GXJHLB();
        }

        private DataTable GET_WUliao(string wlbm)
        {
            DateTime now = DateTime.Now;
            string currentDateTime = now.ToString("yyyy-MM-dd HH:mm:ss");
            K3CloudApi client = new K3CloudApi();
            //用于记录结果
            StringBuilder Info = new StringBuilder();
            //业务对象标识
            string formId = "BD_MATERIAL";
            //查询字段集合，即返回哪些数据，不能为空，根据不同业务单据填写不同的字段名，以下仅为示例
            string fieldKeys = "F_land_DBSL,FMnemonicCode,FName,F_land_Text";
            //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
            var ZBLx = wlbm;
            var param = new QueryParam()
            {
                FormId = formId,
                FieldKeys = fieldKeys,
                FilterString = "FNumber like'%" + ZBLx + "%'",
                TopRowCount = 0,
                StartRow = 0,
                Limit = 120,
                OrderString = "FNumber",
            };
            //调用接口
            var result = client.ExecuteBillQuery(param.ToJson());
            if (dataGridView1.Columns.Count != 0)
            {
                dataGridView1.Columns.Clear();
            }
            /* JsonSerializerSettings settings = new JsonSerializerSettings();
             string jsongStr = JsonConvert.SerializeObject(result, settings);*/
            //转换成标准文档并遍历
            DataTable dataTable = one.ERP_wlxx();
            foreach (var item in result)
            {
                dataTable.Rows.Add(item[0], item[1], item[2], item[3]);
            }
            return dataTable;
        }

        private string GET_KHWLDY(string wlbm)
        {
            DateTime now = DateTime.Now;
            string currentDateTime = now.ToString("yyyy-MM-dd HH:mm:ss");
            K3CloudApi client = new K3CloudApi();
            //用于记录结果
            StringBuilder Info = new StringBuilder();
            //业务对象标识
            string formId = "SAL_CustMatMapping";
            //查询字段集合，即返回哪些数据，不能为空，根据不同业务单据填写不同的字段名，以下仅为示例
            string fieldKeys = "FCustMatName";
            //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
            var ZBLx = wlbm;
            var param = new QueryParam()
            {
                FormId = formId,
                FieldKeys = fieldKeys,
                FilterString = "FMaterialId.FNumber like'%" + ZBLx + "%'",
                TopRowCount = 0,
                StartRow = 0,
                Limit = 120,
                OrderString = "FMaterialId.FNumber",
            };
            //调用接口
            var result = client.ExecuteBillQuery(param.ToJson());
            if (dataGridView1.Columns.Count != 0)
            {
                dataGridView1.Columns.Clear();
            }
            /* JsonSerializerSettings settings = new JsonSerializerSettings();
             string jsongStr = JsonConvert.SerializeObject(result, settings);*/
            //转换成标准文档并遍历
            string bz = "";
            foreach (var item in result)
            {
                bz = item[0].ToString();
            }
            return bz;
        }

        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            //允许数字、退格键和删除键
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }

            // 如果允许小数，并且已有一个小数点，则阻止输入第二个小数点  
            if ((e.KeyChar == '.') && ((sender as System.Windows.Forms.TextBox).Text.IndexOf('.') > -1))
            {
                e.Handled = true;
            }
        }
    }
}
